<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" placeholder="输入验证码" id="tex">
    <input type="button" id="btn1" value="获取验证码">
    <input type="button" value="验证" id="btn2">
    <span id="span"></span>
</body>
<script>
    //定义节点
    var btn1 = document.getElementById('btn1');
    var btn2 = document.getElementById('btn2');
    function yz(n1){
        var a = parseInt(Math.random() * (n1 + 1)); 
        return a;
    }
    
    btn1.onclick = function(){//点击获取验证码
        var num = '';
        var sum1 = yz(9);
        var sum2 = yz(9);
        var sum3 = yz(9);
        var sum4 = yz(9);
        num = sum1+ '' +sum2+ '' +sum3+ '' +sum4;//用空字符进行拼接，实现4个数的显示
        btn1.value = num
        console.log(num);
    }

    btn2.onclick =function() {
        var tex = document.getElementById('tex').value;
        var span = document.getElementById('span');
        var num = btn1.value;//因作用域不同，需重新定义num
        if(tex == num){//字符串的比对
            span.innerHTML = '验证正确';
            span.style.color = 'green';
        }else{
            span.innerHTML = '验证错误';
            span.style.color = 'red';
        }
    }
</script>
</html>